# szdzld insert
import math
import urllib.parse
import webbrowser

import requests

import functions


def get_dv(data):
    str1 = "QR= "
    str2 = " IN"
    pd_data = functions.return_match(str1, str2, data)
    pd = eval(pd_data)
    str3 = "EC= "
    str4 = " QR"
    ec_data = functions.return_match(str3, str4, data)
    ec = eval(ec_data)
    r = float(pd) * 1000 - 6371000
    a = (2 * r + 2 * 6371000) / 2
    dv = math.sqrt((398600000000000 / a) * (1 + ec))
    return dv


def get_c3(dv, data):
    str1 = "QR= "
    str2 = " IN"
    pd_data = functions.return_match(str1, str2, data)
    pd = eval(pd_data)
    r = float(pd) * 1000 - 6371000
    a = (2 * r + 2 * 6371000) / 2
    c3 = math.pow(dv, 2) - math.pow(math.sqrt(398600000000000 / a) * math.sqrt(2), 2)
    return c3 / 1000000


def get_jpl_data(name):
    start_time = urllib.parse.quote(input("Enter start time(xxxx-xx-xx xx:xx):"))
    stop_time = urllib.parse.quote(input("Enter stop time(xxxx-xx-xx xx:xx):"))
    url = f'https://ssd.jpl.nasa.gov/api/horizons.api?format=text&COMMAND=%27{name}%27&OBJ_DATA=%27YES%27' \
          f'&MAKE_EPHEM=%27YES%27&EPHEM_TYPE=%27ELEMENTS%27&START_TIME=%27{start_time}%27&STOP_TIME=%27{stop_time}%27'
    d = requests.get(url)
    data_f = str(d.text).replace("\n", "")
    st1 = "$$SOE"
    st2 = "$$EOE"
    data_match = str(functions.return_match(st1, st2, data_f))
    webbrowser.open_new(url)
    if data_match == "[]":
        return 0
    else:
        return data_match


webbrowser.open_new('https://ssd.jpl.nasa.gov/horizons/time_spans.html')
spacecraft_name = input("Enter space craft name:")
data = get_jpl_data(spacecraft_name)
if data == 0:
    print("DATA IS WRONG")
else:
    flight_dv = get_dv(data)
    flight_c3 = get_c3(flight_dv, data)
    with open("DATA.txt", 'a') as f:
        f.write(f'Spacecraft_name: {spacecraft_name}\nDV: {flight_dv}\nC3: {flight_c3}\n\n')
